package com.hkp.controller;

import com.hkp.pojo.College;
import com.hkp.pojo.ResearchProject;
import com.hkp.service.CollegeService;
import com.hkp.service.ResearchProjectService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;
import java.net.URLEncoder;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/project")
public class ResearchProjectController {
    @Autowired
    private ResearchProjectService projectService;
    @Autowired
    private CollegeService collegeService;

    // 列表页
    @GetMapping("/list")
    public String list(Model model, @RequestParam(required = false) String title,
                       @RequestParam(required = false, defaultValue = "0") Integer collegeId,
                       @RequestParam(required = false, defaultValue = "0") Integer status,
                       @RequestParam(required = false, defaultValue = "1") Integer pageNum,
                       @RequestParam(required = false, defaultValue = "10") Integer pageSize) {
        // 获取所有学院用于下拉选择
        List<College> colleges = collegeService.list();
        model.addAttribute("colleges", colleges);
        
        // 使用MyBatis-Plus的Page对象进行分页查询
        com.baomidou.mybatisplus.extension.plugins.pagination.Page<ResearchProject> page = new com.baomidou.mybatisplus.extension.plugins.pagination.Page<>(pageNum, pageSize);
        
        // 调用service层的分页查询方法（需要在service和mapper中添加）
        List<ResearchProject> projects = projectService.dynamicQuery(title, collegeId == 0 ? null : collegeId, status == 0 ? null : status);
        
        // 手动分页（临时解决方案，后续应该修改service层支持真正的分页查询）
        int total = projects.size();
        int start = (pageNum - 1) * pageSize;
        int end = Math.min(start + pageSize, total);
        List<ResearchProject> pageProjects;
        if (start < total) {
            pageProjects = projects.subList(start, end);
        } else {
            pageProjects = java.util.Collections.emptyList();
        }
        
        // 设置分页信息
        page.setRecords(pageProjects);
        page.setTotal(total);
        
        // 传递分页参数到视图
        model.addAttribute("projects", pageProjects);
        model.addAttribute("current", pageNum);
        model.addAttribute("size", pageSize);
        model.addAttribute("total", total);
        model.addAttribute("pages", (total + pageSize - 1) / pageSize); // 总页数
        
        // 传递查询参数
        model.addAttribute("title", title);
        model.addAttribute("collegeId", collegeId);
        model.addAttribute("status", status);
        
        return "project/list";
    }

    // 添加页面
    @GetMapping("/add")
    public String add(Model model) {
        List<College> colleges = collegeService.list();
        model.addAttribute("colleges", colleges);
        return "project/add";
    }

    // 添加操作
    @PostMapping("/add")
    public String add(ResearchProject project, @RequestParam(required = false) MultipartFile file) throws IOException {
        if (file != null && !file.isEmpty()) {
            // 使用临时目录存储上传文件
            String uploadDir = System.getProperty("java.io.tmpdir") + "/research_project_attachments/";
            File directory = new File(uploadDir);
            if (!directory.exists()) {
                directory.mkdirs();
            }
            String filename = System.currentTimeMillis() + "_" + file.getOriginalFilename();
            File destFile = new File(uploadDir + filename);
            file.transferTo(destFile);
            project.setAttachmentPath(filename); // 只存储文件名
        }
        projectService.save(project);
        return "redirect:/project/list";
    }

    // 编辑页面
    @GetMapping("/edit/{id}")
    public String edit(@PathVariable Integer id, Model model) {
        ResearchProject project = projectService.getById(id);
        List<College> colleges = collegeService.list();
        model.addAttribute("project", project);
        model.addAttribute("colleges", colleges);
        return "project/edit";
    }

    // 编辑操作
    @PostMapping("/edit")
    public String edit(ResearchProject project, @RequestParam(required = false) MultipartFile file) throws IOException {
        if (file != null && !file.isEmpty()) {
            // 使用临时目录存储上传文件
            String uploadDir = System.getProperty("java.io.tmpdir") + "/research_project_attachments/";
            File directory = new File(uploadDir);
            if (!directory.exists()) {
                directory.mkdirs();
            }
            String filename = System.currentTimeMillis() + "_" + file.getOriginalFilename();
            File destFile = new File(uploadDir + filename);
            file.transferTo(destFile);
            project.setAttachmentPath(filename); // 只存储文件名
        }
        projectService.updateById(project);
        return "redirect:/project/list";
    }

    // 下载附件
    @GetMapping("/download/{id}")
    public ResponseEntity<Resource> downloadAttachment(@PathVariable Integer id) {
        try {
            ResearchProject project = projectService.getById(id);
            if (project == null) {
                return ResponseEntity.status(HttpStatus.NOT_FOUND).body(null);
            }
            
            if (project.getAttachmentPath() == null) {
                return ResponseEntity.status(HttpStatus.NOT_FOUND).body(null);
            }
            
            String filename = project.getAttachmentPath();
            // 使用更可靠的路径构建方式
            String uploadDir = System.getProperty("java.io.tmpdir") + File.separator + "research_project_attachments" + File.separator;
            File directory = new File(uploadDir);
            // 确保目录存在
            if (!directory.exists()) {
                directory.mkdirs();
            }
            
            String filePath = uploadDir + filename;
            File file = new File(filePath);
            
            if (!file.exists() || !file.isFile()) {
                return ResponseEntity.status(HttpStatus.NOT_FOUND).body(null);
            }
            
            Resource resource = new FileSystemResource(file);
            // 安全地提取原始文件名，处理文件名中可能不含下划线的情况
            String originalFilename;
            int underscoreIndex = filename.indexOf("_");
            if (underscoreIndex != -1 && underscoreIndex < filename.length() - 1) {
                originalFilename = filename.substring(underscoreIndex + 1);
            } else {
                // 如果没有下划线或下划线在末尾，使用完整文件名
                originalFilename = filename;
            }
            
            try {
                // 对文件名进行URL编码，解决中文文件名问题
                String encodedFilename = URLEncoder.encode(originalFilename, "UTF-8");
                return ResponseEntity.ok()
                        .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename*=UTF-8''" + encodedFilename)
                        .contentType(MediaType.APPLICATION_OCTET_STREAM)
                        .body(resource);
            } catch (Exception e) {
                // 如果编码失败，使用默认方式
                return ResponseEntity.ok()
                        .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + originalFilename + "\"")
                        .contentType(MediaType.APPLICATION_OCTET_STREAM)
                        .body(resource);
            }
        } catch (Exception e) {
            // 捕获所有异常，返回服务器错误状态
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(null);
        }
    }
    
    // 删除操作
    @GetMapping("/delete/{id}")
    public String delete(@PathVariable Integer id) {
        projectService.removeById(id);
        return "redirect:/project/list";
    }

    // 统计分析页面
    @GetMapping("/stats")
    public String stats() {
        return "project/stats";
    }

    // 按学院统计API
    @GetMapping("/api/stats/college")
    @ResponseBody
    public List<Map<String, Object>> collegeStats() {
        return projectService.getProjectCountByCollege();
    }

    // 按状态统计API
    @GetMapping("/api/stats/status")
    @ResponseBody
    public List<Map<String, Object>> statusStats() {
        return projectService.getProjectCountByStatus();
    }
}